<template>
  <div class="pro">
    <searchList @submit="ChangeSubmit" :categoryList="categoryList" />
    <shopTable
      @editProduct="editProduct"
      :data="tableData"
      :page="page"
      :categoryList="categoryList"
      @change="change"
      @removeProduct="removeProduct"
    />
    <a-button type="primary" class="add">
      <router-link :to="{ name: 'ProdouctAdd' }">添加商品</router-link>
    </a-button>
  </div>
</template>
<script>
import searchList from '@/components/shop/search.vue';
import shopTable from '@/components/shop/shopTable.vue';
import categoryApi from '@/api/category';
import api from '@/api/prodouct';
import removeApi from '@/api/removeProduct';

export default {
  data() {
    return {
      tableData: [],
      searchWord: {},
      categoryList: [],
      // 分页显示的数据信息
      page: {
        pageSize: 10,
        current: 1,
        showSizeChanger: true, // 是否可以改变 pageSize
        total: 1, // 数据总数
      },
      categoryObj: {},
    };
  },
  methods: {
    ChangeSubmit(form) {
      this.searchWord = form;
      this.getTableData();
    },
    // 编辑
    editProduct(record) {
      this.$router.push({
        name: 'ProdouctEdit',
        params: {
          id: record.id,
        },
      });
    },
    success() {
      this.$message.success('删除成功');
    },
    // 删除
    removeProduct(record) {
      this.$confirm({
        title: '您确定删除吗',
        content: () => <div style="color:red;">{`您确定删除${record.title}吗`}</div>,
        onOk: () => {
          removeApi
            .remove({
              id: record.id,
            })
            .then((res) => {
              if (res.data.status === 'success') {
                this.success();
                setTimeout(() => {
                  this.getTableData();
                }, 500);
              }
            });
        },
        onCancel() {
          console.log('Cancel');
        },
        class: 'test',
      });
    },
    getTableData() {
      api
        .list({
          // 通过组件通信父传子将数据传递给子组件
          page: this.page.current,
          size: this.page.pageSize,
          ...this.searchWord,
        })
        .then((res) => {
          this.page.total = res.data.data.total;
          this.tableData = res.data.data.data.map((item) => ({
            ...item,
            categoryName: this.categoryObj[item.category].name,
          }));
        });
    },
    change(page) {
      this.page = page;
      this.getTableData();
    },
  },
  async created() {
    // 同步执行 先获取categoryList数据在渲染
    // 获取数据
    await categoryApi.list().then((res) => {
      this.categoryList = res.data.data.data;
      res.data.data.data.forEach((item) => {
        this.categoryObj[item.id] = item; // 用id 的下标做为属性
      });
    });
    this.getTableData();
  },
  components: {
    searchList,
    shopTable,
  },
};
</script>

<style lang="less">
.pro {
  position: relative;
  .add {
    position: absolute;
    top: 24px;
    right: 54px;
  }
}
</style>
